//
//  SISSCalculateResultViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/5/18.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSCalculateResultViewController.h"
#import <math.h>
#import "SISSCalculationResultCell.h"

static NSString *calculateResultCellReuseID = @"calculateResultCellReuseID";

@interface SISSCalculateResultViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *totalLoanLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalRepaymentLabel;
@property (weak, nonatomic) IBOutlet UILabel *interestPaymentLabel;
@property (weak, nonatomic) IBOutlet UILabel *loanMonthLabel;
@property (weak, nonatomic) IBOutlet UILabel *monthRepaymentLabel;

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *interestTitleConstraint;

// 等额本息
/* 还款总额 */
@property (copy, nonatomic) NSString *totalRepayment;
/* 支付利息 */
@property (copy, nonatomic) NSString *interestPayment;
/* 月均还款 */
@property (copy, nonatomic) NSString *monthRepayment;


// 等额本金
/* 还款总额 */
@property (copy, nonatomic) NSString *totalRepaymentPrincipal;
/* 支付利息 */
@property (copy, nonatomic) NSString *interestPaymentPrincipal;
/* 月均还款 */
@property (copy, nonatomic) NSString *monthRepaymentPrincipal;

/* 每月偿还本金 */
@property (assign, nonatomic) CGFloat mothPrincipal;
/* 每月偿还利息 */
@property (assign, nonatomic) CGFloat mothInterest;

/* 是否是等额本金 */
@property (assign, nonatomic) BOOL isAverageCapital;

@end

@implementation SISSCalculateResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"等额本息", @"等额本金"]];
    segmentControl.selectedSegmentIndex = 0;
    segmentControl.tintColor = COLOR(0x249DC5);
    [segmentControl addTarget:self action:@selector(segmentControlbutClick:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentControl;
    if (SCREEN_WIDTH > 320) {
        self.interestTitleConstraint.constant = 14;
    } else {
        self.interestTitleConstraint.constant = 40;
    }
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[SISSCalculationResultCell class] forCellReuseIdentifier:calculateResultCellReuseID];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.model.loanYear;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 12;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSCalculationResultCell *cell = [tableView dequeueReusableCellWithIdentifier:calculateResultCellReuseID forIndexPath:indexPath];
    
    // 还款本金
    CGFloat totalMoney = self.model.totalLoanMoney * 10000;
    // 还款月数
    NSInteger mothCount = self.model.loanYear * 12;
    CGFloat rateR = self.model.reservedRate / 12; // 年利率转月利率
    CGFloat rateC = self.model.commercialRate / 12; // 年利率转月利率
    NSInteger payCurrentMoth = indexPath.section * 12 + indexPath.row + 1;// 当前月数
    CGFloat principal;
    CGFloat interest;
    CGFloat monthlyPayment;
    if (self.isAverageCapital){ // 等额本息
        principal = totalMoney / mothCount;
        
        switch (self.model.calculateType) {
            case SISSCalculateTypeReserved: {
                interest = (totalMoney - principal * payCurrentMoth) * rateR;
            }
                break;
                
            case SISSCalculateTypeCommercial: {
                interest = (totalMoney - principal * payCurrentMoth) * rateC;
                
            }
                break;
                
            case SISSCalculateTypeComBined: {
                
                NSInteger totalMoneyR = self.model.reservedLoanMoney * 10000;
                NSInteger totalMoneyC = self.model.commercialLoanMoney * 10000;
                
                interest = (totalMoneyR - (totalMoneyR / mothCount) * payCurrentMoth) * rateR + (totalMoneyC - (totalMoneyC / mothCount) * payCurrentMoth) * rateC;
                
            }
                break;
                
            default:
                break;
        }
        
        monthlyPayment = principal + interest;
    }  else { // 等额本金
        
        switch (self.model.calculateType) {
                
            case SISSCalculateTypeReserved: {
                principal = totalMoney * rateR * pow((1 + rateR), payCurrentMoth - 1) / (pow(1 + rateR, mothCount) - 1);
                interest = totalMoney * rateR * (pow((1 + rateR), mothCount) - pow((1 + rateR), payCurrentMoth - 1)) / (pow(1 + rateR, mothCount) - 1);
            }
                break;
                
            case SISSCalculateTypeCommercial: {
                principal = totalMoney * rateC * pow((1 + rateC), payCurrentMoth - 1) / (pow(1 + rateC, mothCount) - 1);
                interest = totalMoney * rateC * (pow((1 + rateC), mothCount) - pow((1 + rateC), payCurrentMoth - 1)) / (pow(1 + rateC, mothCount) - 1);
                
                
            }
                break;
                
            case SISSCalculateTypeComBined: {
                
                
                CGFloat totalMoneyR = self.model.reservedLoanMoney * 10000;
                CGFloat totalMoneyC = self.model.commercialLoanMoney * 10000;
                
                CGFloat principalR = totalMoneyR * rateR * pow((1 + rateR), payCurrentMoth - 1) / (pow(1 + rateR, mothCount) - 1);
                CGFloat interestR = totalMoneyR * rateR * (pow((1 + rateR), mothCount) - pow((1 + rateR), payCurrentMoth - 1)) / (pow(1 + rateR, mothCount) - 1);
                CGFloat principalC = totalMoneyC * rateC * pow((1 + rateC), payCurrentMoth - 1) / (pow(1 + rateC, mothCount) - 1);
                CGFloat interestC = totalMoneyC * rateC * (pow((1 + rateC), mothCount) - pow((1 + rateC), payCurrentMoth - 1)) / (pow(1 + rateC, mothCount) - 1);
                principal = principalR + principalC;
                interest = interestR + interestC;
                
            }
                break;
                
            default:
                break;
        }
        
        monthlyPayment = principal + interest;
    }
    
    cell.dict = @{
                  @"period" : [NSString stringWithFormat:@"%zd月",indexPath.row + 1],
                  @"principal" : [NSString stringWithFormat:@"%0.2f",principal],
                  @"interest" : [NSString stringWithFormat:@"%0.2f",interest],
                  @"monthlyPayment" : [NSString stringWithFormat:@"%0.2f",monthlyPayment]
                  };
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"第%zd年",section + 1];
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.textLabel.textColor = COLOR(0x334A60);
    header.textLabel.font = [UIFont systemFontOfSize:16];
//    header.contentView.backgroundColor = MAIN_COLOR;

}

- (void)setModel:(SISSCalculateDeliveryModel *)model {
    [self.view layoutIfNeeded];
    _model = model;
    
    // 还款本金
    CGFloat totalMoney = model.totalLoanMoney * 10000;
    // 还款月数
    NSInteger mothCount = model.loanYear * 12;
    
    CGFloat rate;
    CGFloat mothPay; // 等额本息月供
    CGFloat mothPayPrincipal; // 等额本金月供
    CGFloat sum; // 等额本金还款总额
    switch (model.calculateType) {
        case SISSCalculateTypeReserved: {
            rate = model.reservedRate / 12; // 年利率转月利率
             mothPay = totalMoney * rate *  pow(1 + rate, mothCount) / (pow(1 + rate, mothCount) - 1);
            mothPayPrincipal = (totalMoney / mothCount) + (totalMoney - 0) * rate;
            // 等额本金还款总额
            sum = mothCount * (totalMoney * rate - rate * (totalMoney / mothCount) * (mothCount - 1) / 2 + totalMoney / mothCount);
            
        }
            break;
            
        case SISSCalculateTypeCommercial: {
            rate = model.commercialRate / 12; // 年利率转月利率
            mothPay = totalMoney * rate *  pow(1 + rate, mothCount) / (pow(1 + rate, mothCount) - 1);
            mothPayPrincipal = (totalMoney / mothCount) + (totalMoney - 0) * rate;
            sum = mothCount * (totalMoney * rate - rate * (totalMoney / mothCount) * (mothCount - 1) / 2 + totalMoney / mothCount);
        }
            break;
            
        case SISSCalculateTypeComBined: {
            CGFloat rateR = model.reservedRate / 12; // 年利率转月利率
            CGFloat rateC = model.commercialRate / 12; // 年利率转月利率
            CGFloat totalMoneyR = model.reservedLoanMoney * 10000;
            CGFloat totalMoneyC = model.commercialLoanMoney * 10000;
            
            CGFloat mothPayR = totalMoneyR * rateR *  pow(1 + rateR, mothCount) / (pow(1 + rateR, mothCount) - 1);
            CGFloat mothPayC = totalMoneyC * rateC *  pow(1 + rateC, mothCount) / (pow(1 + rateC, mothCount) - 1);
            mothPay = mothPayR + mothPayC;
            
            CGFloat mothPayPrincipalR = (totalMoneyR / mothCount) + (totalMoneyR - 0) * rateR;
            CGFloat mothPayPrincipalC = (totalMoneyC / mothCount) + (totalMoneyC - 0) * rateC;
            mothPayPrincipal = mothPayPrincipalR + mothPayPrincipalC;
            
            CGFloat sumC = mothCount * (totalMoneyR * rateC - rateC * (totalMoneyC / mothCount) * (mothCount - 1) / 2 + totalMoneyC / mothCount);
            CGFloat sumR = mothCount * (totalMoneyR * rateR - rateR * (totalMoneyR / mothCount) * (mothCount - 1) / 2 + totalMoneyR / mothCount);
            sum = sumC + sumR;
        }
            break;
            
        default:
            break;
    }

    self.monthRepayment = [NSString stringWithFormat:@"%0.2f元",mothPay];
    self.totalRepayment = [NSString stringWithFormat:@"%0.2f万",mothPay * mothCount * 0.0001];
    self.interestPayment = [NSString stringWithFormat:@"%0.2f万",mothPay * mothCount * 0.0001 - model.totalLoanMoney];
    
    self.monthRepaymentPrincipal = [NSString stringWithFormat:@"%0.2f元",mothPayPrincipal];
    self.totalRepaymentPrincipal = [NSString stringWithFormat:@"%0.2f万",sum * 0.0001];
    self.interestPaymentPrincipal = [NSString stringWithFormat:@"%0.2f万",sum * 0.0001 - model.totalLoanMoney];
  
    
    // 等额本息
    //每月应还本金：每月应还本金=贷款本金×月利率×(1+月利率)^(还款月序号-1)÷〔(1+月利率)^还款月数-1〕
//    每月应还利息：贷款本金×月利率×〔(1+月利率)^还款月数-(1+月利率)^(还款月序号-1)〕÷〔(1+月利率)^还款月数-1〕
//        CGFloat payInterest = totalMoney * rate * (pow(1 + rate, mothCount) - pow(1 + rate,  还款月序号-1)) / (pow(1 + rate, mothCount) - 1);
    
    //月供：每月月供额=〔贷款本金×月利率×(1＋月利率)＾还款月数〕÷〔(1＋月利率)＾还款月数-1〕
   
    
    // 等额本金
    //每月应还本金：贷款本金÷还款月数
    //每月应还利息：剩余本金×月利率=(贷款本金-已归还本金累计额)×月利率
//    CGFloat payInterestM = (totalMoney - 已归还本金累计额) * rate;
    //月供：(贷款本金÷还款月数)+(贷款本金-已归还本金累计额)×月利率
    
    
    self.totalLoanLabel.text = [NSString stringWithFormat:@"%.2f万",model.totalLoanMoney];
    self.loanMonthLabel.text = [NSString stringWithFormat:@"%zd月",mothCount];
    self.totalRepaymentLabel.text = self.totalRepayment;
    self.interestPaymentLabel.text = self.interestPayment;
    self.monthRepaymentLabel.text = self.monthRepayment;
    
    [self.tableView reloadData];
}

- (void)segmentControlbutClick:(UISegmentedControl *)sender {
    
    
    if (sender.selectedSegmentIndex == 0) {
        
//        self.tipLabel.hidden = YES;
        self.isAverageCapital = NO;
        self.totalRepaymentLabel.text = self.totalRepayment;
        self.interestPaymentLabel.text = self.interestPayment;
        self.monthRepaymentLabel.text = self.monthRepayment;
       [self.tableView reloadData];
    } else {
        self.isAverageCapital = YES;
//        self.tipLabel.hidden = NO;
//        self.tipLabel.text = @"首月后每月递减5元";
        self.totalRepaymentLabel.text = self.totalRepaymentPrincipal;
        self.interestPaymentLabel.text = self.interestPaymentPrincipal;
        self.monthRepaymentLabel.text = self.monthRepaymentPrincipal;
        [self.tableView reloadData];
    }
}
@end
